﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;


public class FileManage{

    #region   /*存储资源*/
    public static void StoreFile(string filePath,byte[] info)
    {
        FileInfo f = new FileInfo(filePath);
        StoreFile(f.DirectoryName, f.Name, info);
    }

    /// <summary>
    /// 存储数据，自动创建文件夹路径，覆盖旧文件
    /// </summary>
    /// <param name="folderPath">存储的文件夹路径</param>
    /// <param name="fileName">文件名(带后缀)</param>
    /// <param name="info">保存的字节内容</param>
    public static void StoreFile(string folderPath, string fileName, byte[] info)
    {
        //如果没有该文件夹则创建(包括其不存在的父级目录)
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        //组合建立绝对文件路径
        string fileFullName = folderPath + "/"+fileName;
        //if (extension != null)//是否添加扩展名
        //{
        //    fileFullName += extension;
        //}
        //创建文件对象
        FileInfo fileInfo = new FileInfo(fileFullName);
        //如果文件存在,则删除覆盖
        if (fileInfo.Exists)
            fileInfo.Delete();
        //创建stream将数据写入文件对象
        Stream sw = fileInfo.Create();
        //写入  
        sw.Write(info, 0, info.Length);
        sw.Flush();
        //关闭流  
        sw.Close();
        //销毁流  
        sw.Dispose();

        Debug.Log("-------------" + fileFullName + "成功保存到本地~");
    }
    #endregion

    #region /*读取资源*/
    public static byte[] LoadFile(string filePath)
    {
        try
        {
            if(!File.Exists(filePath))
            {
                Debug.Log("---------there are dont have this file");
                return null;
            }

            FileInfo f = new FileInfo(filePath);
            byte[] readInfo=null;
            using ( Stream sw = f.OpenRead())
            {
                readInfo = new byte[sw.Length];
                sw.Read(readInfo, 0,readInfo.Length);
                sw.Close();
            }

            return readInfo;

        }
        catch
        {
            Debug.Log("-----------readFile Error");
            return null;
        }
    }
    #endregion 读取资源
}
